import argparse
import datetime
import os
import uuid
from pathlib import Path

import yaml


class Util:

    # 获取项目绝对路径
    @staticmethod
    def get_project_dir():
        root = Path(__file__).resolve().parent.parent.parent
        return f"{root}{os.sep}"

    # 获取参数文件路径
    @staticmethod
    def get_config_file_path():
        default_config_file = "config.yaml"
        if os.path.exists(Util.get_project_dir() +"data/."+ default_config_file):
            config_file = "data/."+ default_config_file
        else:
            config_file = Util.get_project_dir() + default_config_file
        return config_file

    # 获取随机文件保存路径
    @staticmethod
    def get_random_file_path(dir: str, ex_name: str):
        file_name = f"{datetime.now().date()}_{uuid.uuid4().hex}.{ex_name}"
        file_path = os.path.join(dir, file_name)
        return file_path

    # 获取配置文件
    @staticmethod
    def get_config():
        parser = argparse.ArgumentParser(description="Server Configuration")
        config_file = Util.get_config_file_path()
        parser.add_argument("--config_path", type=str, default=config_file)
        args = parser.parse_args()
        print(f"loading configuration from {args.config_path}")
        with open (args.config_path,"r",encoding ="utf-8") as f:
            config = yaml.safe_load(f)
    #     初始化文件目录
        Util.init_output_dir(config)
        return config


    # 自动扫描所有层级的output——dir配置
    @staticmethod
    def init_output_dir(config):
        results = set()
        def _traverse(data):
            if isinstance(data, dict):
                if "output_dir" in data:
                    results.add(data["output_dir"])
                for value in data.values():
                    _traverse(value)
            elif isinstance(data, list):
                for item in data:
                    _traverse(item)
        _traverse(config)
        for dir_path in results:
            try:
                os.makedirs(Util.get_project_dir()+dir_path,exist_ok=True)
            except PermissionError:
                print(f"警告，无法创建目录{dir_path}<UNK>")


if __name__ == '__main__':
    print(Util.get_project_dir())
    print(Util.get_config())